package youleche.com.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import youleche.com.business.BRentVehicleInfo;
import youleche.com.business.BSeller;
import youleche.com.business.BVehicleImageInfo;
import youleche.com.business.BVehicleInfo;
import youleche.com.caches.CacheFactory;
import youleche.com.common.IDFactory;
import youleche.com.model.MVehicleImageInfo;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片工厂
 * @author shenyuchuan
 *
 */
public class ImageFactory {
	/**
	 * 生成电话号码图片
	 * @param out 输出流
	 * @param phoneNum 电话号码
	 * @author shenyuchuan
	 */
	public static void generateCellPhoneNumber(OutputStream out, String phoneNum){
		int width = 200;
		int height = 28;
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		g.setBackground(Color.WHITE);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.RED);
		g.setFont(new Font("隶书",Font.BOLD, 24));
		g.drawString(phoneNum, 1, 20);
		bi.flush();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(1.0f, false);
		encoder.setJPEGEncodeParam(param);
		try {
			encoder.encode(bi);
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}finally{
			g.dispose();
		}
	}
	
	/**
	 * 生成验证码
	 * @param out 输出流
	 * @author shenyuchuan
	 */
	public static void generateValidateCode(OutputStream out){
		int width = 150;
		int height = 28;
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		g.setBackground(Color.WHITE);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.RED);
		g.setFont(new Font("隶书",Font.BOLD, 24));
		g.drawString("1121", 1, 20);
		bi.flush();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(1.0f, false);
		encoder.setJPEGEncodeParam(param);
		try {
			encoder.encode(bi);
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}finally{
			g.dispose();
		}
	}
	
	/**
	 * 批量处理图片
	 * @param imgIds 图片id字符集
	 * @param tempDir 临时目录
	 * @param normalDir 正式目录
	 * @param vehicleId 车辆信息ID
	 */
	public static void handleImagesByBatch(String imgIds, String tempDir, String normalDir, String vehicleId){
		if("".equals(imgIds)){
			return;
		}
		
		if(!imgIds.contains("^")){
			return;
		}
		
		imgIds = imgIds.substring(0, imgIds.length() - 1);		
		String[] idArr = imgIds.split("\\^");
		String homeImgId = "";
		//首页图片Id
		for (int i = 0; i < idArr.length; i++) {
			if(idArr[i].contains("home")){
				homeImgId =idArr[i]; 
				break;
			}else{
				return;
			}
		}
		
		String extName = homeImgId.split("\\*")[0].split("\\.")[1];
		String homeImageId = homeImgId.split("\\*")[0].split("\\.")[0] + "-300_300." + extName;
		List<String> imgNameList = new LinkedList<String>();
		List<String> imgIdList = new LinkedList<String>();
		imgIdList.add(homeImgId.split("\\*")[0].split("\\.")[0] + "." + extName);
		imgNameList.add(homeImgId.split("\\*")[0].split("\\.")[0] + "-normal." + extName);
		imgNameList.add(homeImgId.split("\\*")[0].split("\\.")[0] + "-200_200." + extName);
		for (int i = 0; i < idArr.length; i++) {
			if(!idArr[i].contains("home")){
				String ename = idArr[i].split("\\.")[1];
				String name = idArr[i].split("\\.")[0];
				imgNameList.add(name + "-normal." + ename);
				imgNameList.add(name + "-200_200." + ename);
				imgIdList.add(name + "." + extName);
			}
		}
		//更新信息的ImageId
		updateVehicleImageIdByVehicleId(homeImageId, vehicleId);		
		
		//批量插入图片信息到数据vehicleImageInfo(200-200/normal/home)
		//批量复制图片到正式文件夹
		asynAdd(homeImageId, "2", vehicleId);
		if(imgNameList !=null || imgNameList.size() >0){
			for (String imgId : imgNameList) {
				if(imgId.contains("normal")){
					asynAdd(imgId, "3", vehicleId);
				}else{
					asynAdd(imgId, "1", vehicleId);					
				}
				FileUtil.copyFile(tempDir + imgId, normalDir + imgId);
			}
		}
		
		FileUtil.copyFile(tempDir + homeImageId, normalDir + homeImageId);
		//批量删除文件
		for (String id : imgIdList) {
			deleteRelativeImagesByBatch(id, tempDir);
		}
		
		
		
	}
	
	/**
	 * 批量处理图片(针对租车信息)
	 * @param imgIds 图片id字符集
	 * @param tempDir 临时目录
	 * @param normalDir 正式目录
	 * @param rentId 租车信息ID
	 */
	public static void handleImagesByBatch_rent(String imgIds, String tempDir, String normalDir, String rentId){
		if("".equals(imgIds)){
			return;
		}
		
		if(!imgIds.contains("^")){
			return;
		}
	
		imgIds = imgIds.substring(0, imgIds.length() - 1);		
		String[] idArr = imgIds.split("\\^");
		String homeImgId = "";
		//首页图片Id
		for (int i = 0; i < idArr.length; i++) {
			if(idArr[i].contains("home")){
				homeImgId =idArr[i]; 
				break;
			}else{
				return;
			}
		}
		
		String extName = homeImgId.split("\\*")[0].split("\\.")[1];
		String homeImageId = homeImgId.split("\\*")[0].split("\\.")[0] + "." + extName;
		List<String> imgNameList = new LinkedList<String>();
		List<String> imgIdList = new LinkedList<String>();
		imgIdList.add(homeImgId.split("\\*")[0].split("\\.")[0] + "." + extName);
		imgNameList.add(homeImgId.split("\\*")[0].split("\\.")[0] + "." + extName);
		for (int i = 0; i < idArr.length; i++) {
			if(!idArr[i].contains("home")){
				String ename = idArr[i].split("\\.")[1];
				String name = idArr[i].split("\\.")[0];
				imgNameList.add(name + "." + ename);
				imgIdList.add(name + "." + extName);
			}
		}
		//更新信息的ImageId
		updateRentVehicleImageIdByVehicleId(homeImageId, rentId);		
		
		//批量插入图片信息到数据vehicleImageInfo(200-200/normal/home)
		//批量复制图片到正式文件夹
		//asynAdd(homeImageId, "0", rentId);
		if(imgNameList !=null || imgNameList.size() >0){
			for (String imgId : imgNameList) {
				asynAdd(imgId, "1", rentId);	
				FileUtil.copyFile(tempDir + imgId, normalDir + imgId);
			}
		}
		
		//FileUtil.copyFile(tempDir + homeImageId, normalDir + homeImageId);
		//批量删除文件
		for (String id : imgIdList) {
			deleteRelativeImagesByBatch(id, tempDir);
		}
		
		
		
	}
	
	/**
	 * 添加图片信息
	 * @param fileName 图片文件名
	 * @param type 图片类型
	 * @param vehicleId 车辆信息Id
	 */
	private static void asynAdd(String fileName, String type, String vehicleId){
		MVehicleImageInfo image = new MVehicleImageInfo();
		image.setAddTime(DateUtil.getNowDate());
		image.setImageId(IDFactory.getId("meileche", "vehicleImageInfo"));
		image.setImagePath(fileName);
		image.setImageType(type);
		image.setSellerId("meileche");
		image.setVehicleId(vehicleId);
		try {			
			BVehicleImageInfo handler = new BVehicleImageInfo();
			handler.addVehicleImageInfo(image);
		} catch (Exception e) {
		}
	}
	
	/**
	 * 更新车辆的图片Id（首页）
	 * @param imageId 图片ID
	 * @param vehicleId 车辆ID
	 */
	@SuppressWarnings("static-access")
	private static void updateVehicleImageIdByVehicleId(String imageId, String vehicleId){
		BVehicleInfo handler = new BVehicleInfo();
		try {
			handler.updateImageIdByVehicleId(imageId, vehicleId);
			CacheFactory.getVehicleCache().updateCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 更新租车信息的图片Id
	 * @param imageId 图片ID
	 * @param rentId 租车信息ID
	 */
	@SuppressWarnings("static-access")
	private static void updateRentVehicleImageIdByVehicleId(String imageId, String rentId){
		BRentVehicleInfo handler = new BRentVehicleInfo();
		try {
			handler.updateImageIdByRentId(imageId, rentId);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 批量删除一个Id相关图片(在临时文件)
	 * @param imgId 图片id
	 * @param fileDic 图片文件路径
	 */
	public static void deleteRelativeImagesByBatch(String imgId, String fileDic){
		if("".equals(imgId)){
			return;
		}
		
		if(!imgId.contains(".")){
			return;
		}
		
		List<String> imgNameList = new LinkedList<String>();
		String preId = imgId.split("\\.")[0];
		String extName = imgId.split("\\.")[1];
		imgNameList.add(preId +  "-normal" + "." + extName);
		imgNameList.add(preId +"-200_200"+  "." + extName);
		imgNameList.add(preId +"-100_100"+ "." +  extName);
		imgNameList.add(preId +"-300_300"+ "." +  extName);
		
		for (String imgName : imgNameList) {
			File file = new File(fileDic +imgName);
			if(file.exists()){
				file.delete();
			}
		}	
	}
	
	/**
	 * 删除认证图片
	 * @param userId 用户ID
	 * @param fileDic 文件目录
	 */
	public static void deleteCertifyImage(String userId, String fileDic){
		File file = new File(fileDic +fileDic);
		if(file.exists()){
			file.delete();
		}
	}
}
